package com.xiaoma.h5testdemo.common.utils

import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import android.util.Log
import java.util.Locale

/**
 * author: liangjingbo
 * date: 2023/11/23
 * describe:
 */
object LanguageUtils {
    private val TAG = LanguageUtils::class.java.simpleName + "_XMTag"

    /**当前是不是中文环境*/
    fun isChinese(context: Context): Boolean {
        val curLanguage = getLanguage(context)
        return isTargetLanguage(curLanguage, "zh")
    }

    /**当前是不是中文环境*/
    fun isEnglish(context: Context): Boolean {
        val curLanguage = getLanguage(context)
        return isTargetLanguage(curLanguage, "en")
    }

    /**当前是不是中文环境*/
    fun isAr(context: Context): Boolean {
        val curLanguage = getLanguage(context)
        return isTargetLanguage(curLanguage, "ar")
    }

    /**当前是不是俄罗斯文环境*/
    fun isRu(context: Context): Boolean {
        val curLanguage = getLanguage(context)
        return isTargetLanguage(curLanguage, "ru")
    }

    /**当前是不是波斯文环境*/
    fun isFa(context: Context): Boolean {
        val curLanguage = getLanguage(context)
        return isTargetLanguage(curLanguage, "fa")
    }


    private fun getLanguage(context: Context): String? {
        val locale = context.resources.configuration.locale
        val language = locale.language
        Log.i(TAG, "isChinese() language:$language")
        return language
    }

    fun setAppLanguage(context: Context, language: String) {
        val locale = Locale(language) // 阿拉伯文语言代码
        Locale.setDefault(locale)

        val config = Configuration()
        config.locale = locale

        val resources: Resources = context.resources
        resources.updateConfiguration(config, resources.displayMetrics)
    }

    private fun isTargetLanguage(curLanguage: String?, targetLanguage: String): Boolean {
        return curLanguage != null && curLanguage.contains(targetLanguage, true)
    }


}